/**
 * 食药公用js
 * 
 * */
define([
    'base',
    'bootstrapDialog',
    'bootstrapTable',
    'highcharts',
    'exporting',
    'highchartsCN',
    'sandSignika',
    'jqViewer',
    'jqPrint',
    "css!global/plugins/viewer/viewer.min.css"
], function (base, BootstrapDialog,highcharts,jqPrint) {
    //默认加载基础库
    base();

    /**
     * form表单转换成json
     */
    function getFormJson(form) {
        var data = {};
        var a = $(form).serializeArray();
        $.each(a, function () {
            if (data[this.name] !== undefined) {
                if (!data[this.name].push) {
                    data[this.name] = [data[this.name]];
                }
                data[this.name].push(this.value || '');
            } else {
                data[this.name] = this.value || '';
            }
        });
        return data;
    }
    
    function remove_ie_header_and_footer() {
    	  var hkey_path;
    	  hkey_path = "HKEY_CURRENT_USER\\Software\\Microsoft\\Internet Explorer\\PageSetup\\";
    	  try {
    	   var RegWsh = new ActiveXObject("WScript.Shell");
    	   RegWsh.RegWrite(hkey_path + "header", "");
    	   RegWsh.RegWrite(hkey_path + "footer", "");
    	  } catch (e) {
    	  }
    	 }

    return {
        list: function (stepNode) {
            var myTable = $('#dataList');
            var tableRefresh = function () {
                myTable.bootstrapTable('refresh', {url: stepNode+'/api.json'})
            };
            //table按需刷新动作
            var doAction = function (obj) {
                myTable.bootstrapTable('refresh', {url: stepNode+'/api.json?pid=' + obj.id})
            };

            //table当前行的响应事件
            window.operateEvents = {
                'click .preExamineClaim': function (e, value, row) {
                	 $.baseUtils.claimStatus({
                         row: row,
                         tableName: myTable,
                         title:'预审认领',
                         nameText: '食药申请',
                         nameValue: row.itemName,
                         applyStatus:2,
                         url: '../save/action'
                     });
                },
                'click .evaluate': function (e, value, row) {
                	 window.location.href = 'evaluate/'+row.itemId;
               },
                'click .preExamineAgree': function (e, value, row) {
                	   winModal({ 
                		   row: row,
                		   title:'预审通过意见',
                		   status:4,
                		   btName:'预审通过'
                	   });
               },
               'click .preExamineRefuse': function (e, value, row) {
	            	   winModal({ 
	            		   row: row,
	            		   title:'预审拒绝意见',
	            		   status:3,
	            		   btName:'预审拒绝'
	            	   });
                 },
               
               'click .examineClaim': function (e, value, row) {
              	 $.baseUtils.claimStatus({
              	     row: row,
                     tableName: myTable,
                     title:'初审认领',
                     nameText: '食药申请',
                     nameValue: row.itemName,
                     applyStatus:5,
                     url: '../save/action'
                   });
               },
               'click .examineAgree': function (e, value, row) {
            	   winModal({ 
            		   row: row,
            		   title:'初审通过意见',
            		   status:7,
            		   btName:'审核通过'
            	   });
                 },
                'click .examineRefuse': function (e, value, row) {
                	 winModal({ 
	            		   row: row,
	            		   title:'初审拒绝意见',
	            		   status:6,
	            		   btName:'审核拒绝'
	            	   });
                 },
                 'click .reExamineClaim': function (e, value, row) {
                	 $.baseUtils.claimStatus({
                	     row: row,
                         tableName: myTable,
                         title:'复审认领',
                         nameText: '食药申请',
                         nameValue: row.itemName,
                         applyStatus:8,
                         url: '../save/action'
                     });
                },
                'click .reExamineAgree': function (e, value, row) {
                	   winModal({ 
                		   row: row,
                		   title:'复审通过意见',
                		   status:10,
                		   btName:'审核通过'
                	   });
               },
               'click .reExamineRefuse': function (e, value, row) {
		            	   winModal({ 
		            		   row: row,
		            		   title:'复审拒绝意见',
		            		   status:10,
		            		   btName:'审核拒绝'
		            	   });
                 },
                'click .detail': function (e, value, row) {
                    //食药申请模板
                    window.location.href = row.itemId;
                },
                'click .delete': function (e, value, row) {
                    $.baseUtils.oneDelete({
                        row: row,
                        tableName: myTable,
                        nameText: '食药申请',
                        nameValue: row.itemName,
                        url: '../delete/action'
                    });
                }
            };

            
          //table当前行的响应事件
            window.printEvents = {
             'click .print': function (e, value, row) {
                         //食药申请模板
                         window.location.href = 'print/'+row.itemId;
                    },
            'click .companyLicense': function (e, value, row) {
                    //食药申请模板
                    window.location.href = '/fooddrugApply/view/basePrint/'+row.itemId+'/1';
                },
            'click .rentalContract': function (e, value, row) {
                //食药申请模板
                window.location.href = '/fooddrugApply/view/basePrint/'+row.itemId+'/2';
            },
            'click .layout': function (e, value, row) {
                //食药申请模板
                window.location.href = '/fooddrugApply/view/basePrint/'+row.itemId+'/3';
            },
            'click .operatingProcedures': function (e, value, row) {
                //食药申请模板
                window.location.href = '/fooddrugApply/view/basePrint/'+row.itemId+'/4';
            },
            'click .orientationMap': function (e, value, row) {
                //食药申请模板
                window.location.href = '/fooddrugApply/view/basePrint/'+row.itemId+'/5';
            },
            'click .legal': function (e, value, row) {
                //食药申请模板
                window.location.href = '/fooddrugApply/view/memberPrint/'+row.itemId+'/2';
            },
            'click .employee': function (e, value, row) {
                //食药申请模板
                window.location.href = '/fooddrugApply/view/memberPrint/'+row.itemId+'/3';
            },
            'click .license': function (e, value, row) {
                //食药申请模板
                window.location.href = '/fooddrugApply/view/licensePrint/'+row.itemId;
            },
            'click .device': function (e, value, row) {
                //食药申请模板
                window.location.href = '/fooddrugApply/view/devicePrint/'+row.itemId;
            }
       
            };
            //table表格
            myTable.bootstrapTable({
                url: stepNode+'/api.json', // 接口 URL 地址
                cache: false, // 不缓存
                striped: true, // 隔行加亮
                pagination: true, // 开启分页功能
                sidePagination: 'server',//服务端分页
                sortOrder: 'desc', // 设置排序为反序 desc
                fixedColumns: true,//自动修复
                queryParams: queryParams,//搜索附加参数
                smartDisplay: false, // 智能显示 pagination 和 cardview 等
                toolbar: ".toolBar", //顶部工具菜单
                toolbarAlign: "right", //顶部工具位置
                mobileResponsive: "true", //手机模式自适应宽度（自动变成卡片模式）
                columns: [
                    {
                        field: 'id',
                        title: '申请编号',
                        align: 'center',
                        width: '5%'
                    }, {
                        field: 'itemName',
                        title: '公司信息',
                        width: '30%',
                        formatter: function (value, row, index) {
                            return '<i class="fa fa-hashtag text-primary" aria-hidden="true"></i>&emsp;<b>' + value + '</b><br/>&emsp;'
                        }
                    },
                    {
                        field: 'createName',
                        title: '申请信息',
                        width: '10%',
                        formatter: function (value, row, index) {
                            return '<i class="fa fa-user" aria-hidden="true"></i>&emsp;' + value + '<br /><i class="fa fa-clock-o" aria-hidden="true"></i>&emsp;' + row.createTime
                        }
                    }, {
                        field: 'updateName',
                        title: '更新信息',
                        width: '10%',
                        formatter: function (value, row, index) {
                            return '<i class="fa fa-user" aria-hidden="true"></i>&emsp;' + value + '<br /><i class="fa fa-clock-o" aria-hidden="true"></i>&emsp;' + row.updateTime
                        }
                    }, {
                        field: 'itemStatus',
                        title: '申请状态',
                        align: 'center',
                        width: '5%',
                        //申请状态（0未提交暂存；1待预审；2预审中；3预审拒绝被退回；4预审通过待核准；5核准中；6核准拒绝被退回；7核准通过；8放弃作废)
                        formatter: function (value, row, index) {
                            var result = "<span class=\"label label-white\">未知</span>";
                            switch (value) {
                                case 0:
                                    result = "<span class=\"label label-default\">未提交</span>";
                                    break;
                                case 1:
                                    result = "<span class=\"label label-warning\">待预审</span>";
                                    break;
                                case 2:
                                    result = "<span class=\"label label-info\">预审中</span>";
                                    break;
                                case 3:
                                    result = "<span class=\"label label-danger\">预审拒绝</span>";
                                    break;
                                case 4:
                                    result = "<span class=\"label label-warning\">待初审</span>";
                                    break;
                                case 5:
                                    result = "<span class=\"label label-info\">初审中</span>";
                                    break;
                                case 6:
                                    result = "<span class=\"label label-danger\">初审拒绝</span>";
                                    break;
                                case 7:
                                    result = "<span class=\"label label-primary\">待复审</span>";
                                    break;
                                case 8:
                                    result = "<span class=\"label label-inverse\">复审中</span>";
                                    break;
                                case 9:
                                    result = "<span class=\"label label-inverse\">复审拒绝</span>";
                                    break;
                                case 10:
                                    result = "<span class=\"label label-inverse\">审核通过</span>";
                                    break;
                                case 11:
                                    result = "<span class=\"label label-inverse\">作废</span>";
                                    break;
                                default:
                                    break;
                            }
                            return result;
                        }
                    }, {
                        field: 'action',
                        title: '操作',
                        align: 'center',
                        width: '20%',
                        formatter: operateFormatter,
                        events: operateEvents
                    },
                    {
                        field: 'print',
                        title: '打印',
                        align: 'center',
                        width: '5%',
                        formatter: printFormatter,
                        events: printEvents
                    }
                ]
            });

            //搜索刷新
            $('#search').on('click', function () {
                tableRefresh();
            });

  
            //刷新
            $(".toolbar-refresh").on('click', function () {
                tableRefresh();
            });

            //批量修改状态
            $(".toolbar-batchStatus").on('click', function () {
                var entityList = myTable.bootstrapTable('getSelections');
                var row = [], names = [];
                $.each(entityList, function (i, v) {
                    names.push(v.itemName);
                    row.push(v.id);
                });
                if (row.length > 0) {
                    $.baseUtils.batchAction({
                        row: row,
                        tableName: myTable,
                        nameText: '食药申请',
                        nameValue: names,
                        url: '../status/batchAction'
                    });
                } else {
                    msgTool.error("请选择虽少一条记录后再操作", "信息提示");
                }

            });


            //搜索参数传递
            function queryParams(params) {
                params.id = $("#id").val();
                params.itemName = $("#itemName").val();
                params.applyStatus = $("#applyStatus").val();
                return {
                    limit: params.limit,
                    offset: params.offset,
                    applyStatus: params.applyStatus,
                    itemName: params.itemName,
                    id: params.id
                };
            }

            //回显
            function responseHandler(res) {
                return res.rows;
            }

            //打印列表参数
            function printFormatter(value, row, index) {
                var tempCode = "";
                tempCode += '<button type="button" class="print btn btn-white"><i class="fa fa-print"></i>&nbsp;打印&nbsp;</button>';
                return '<div class="btn-group btn-group-xs">' + tempCode + '</div>';
            } 
            //模态框
            function winModal(obj) {
                BootstrapDialog.show({
                    type: BootstrapDialog.TYPE_DEFAULT,
                    tabindex: null,//解决select2搜索框失去焦点的问题
                    title: obj.title,
                    closable: true,	//关闭箭头启动
                    closeByBackdrop: false,	//点击空白不消失
                    closeByKeyboard: true,//ESC取消禁用
                    message: $('<div></div>').load('../save/form.html'),
                    data: {
                        'row': obj.row
                    },
                    buttons: [{
                        label: '取消',
                        cssClass: 'btn-white cancel',
                        icon: 'fa fa-times',
                        action: function (dialog) {
                            dialog.close();
                        }
                    }, {
                        label: obj.btName,
                        //hotkey: 13,//回车提交
                        cssClass: 'btn-primary',
                        icon: 'fa fa-check',
                        action: function (dialog) {
                            //返回验证结果
                                $.baseUtils.ajax({
                                    dialog: dialog,
                                    url: '../save/action',
                                    data: $("#winModal").serialize(),
                                    text: "保存",
                                    isTable: true,
                                    tableName: '#dataList',
                                    isDialog: true
                                })
                        }
                    }],
                    onshown: function (dialog) {
                    	var row=obj.row;
                        if (row != null) {
                            $('#id').val(row.id);
                            $('#itemId').val(row.itemId);
                            $('#itemName').val(row.itemName);
                            $('#itemType').val(row.itemType);
                            $('#status').val(obj.status);
                        }
                    }
                });
            }
        },
        template: function (flowId) {
            //添加食药申请步骤
            $("#addStep").on('click', function () {
                var length = $("form").length + 1;
                $("#step-box").append("<form class=\"form-horizontal\" name=\"flowTemplateForm\" id=\"flowTemplate_" + length + "\" method=\"post\" role=\"form\"><input value=\"" + flowId + "\" name=\"flowId\" type=\"hidden\"><div class=\"panel panel-default\"><div class=\"panel-heading\"><b class=\"text step-title\">食药申请步骤" + length + "：</b><div class=\"pull-right\"><button onclick=\"$(this).parents('.panel').remove()\" class=\"btn btn-danger\">&nbsp;删除&nbsp;</button></div></div><div class=\"panel-body\"><div class=\"form-group\"><div class=\"col-sm-3\"><label class=\"control-label\">步骤名称：</label><input name=\"stepName\" class=\"form-control\" type=\"text\" required aria-required=\"true\" maxlength='30' placeholder=\"请输入步骤名称\"></div><div class=\"col-sm-3\"><label class=\"control-label\">上个部门小组编号：</label><input name=\"lastOrgId\" class=\"form-control\" type=\"number\" placeholder=\"请输入上个部门小组编号\" required='required'></div><div class=\"col-sm-3\"><label class=\"control-label\">当前部门小组编号：</label><input name=\"orgId\" class=\"form-control\" type=\"number\" required aria-required=\"true\" placeholder=\"请输入当前部门小组编号\"></div><div class=\"col-sm-3\"><label class=\"control-label\">下个部门小组编号：</label><input name=\"nextOrgId\" class=\"form-control\" type=\"number\" placeholder=\"请输入下个部门小组编号\" required='required'></div></div><div class=\"form-group\"><div class=\"col-sm-3\"><label class=\"control-label\">节点类型：</label><select name=\"nodeType\" class=\"form-control\"><option value=\"0\" selected>普通节点</option><option value=\"1\">开始节点</option><option value=\"2\">结束节点</option></select></div><div class=\"col-sm-9\"><label class=\"control-label\">附加参数：</label><input name=\"attrs\" class=\"form-control\" type=\"text\" required aria-required=\"true\" placeholder=\"请输入附加参数\"></div></div></div></div></form>");
            });
            //提交食药申请
            $("#doSubmit").on('click', function () {
                    var dataFormStatus = false;
                    var form = $("form[name='flowTemplateForm']");
                    $.each(form, function () {
                        dataFormStatus = $(this).validate().form();
                    });
                    dataFormStatus = true;
                    if (dataFormStatus) {
                        var length = form.length;
                        //定义要传递的数组
                        var flowTemplateList = [];
                        for (var i = 1; i <= length; i++) {
                            var formJson = getFormJson($("#flowTemplate_" + i));
                            flowTemplateList.push(formJson);
                        }
                        $.ajax({
                            url: "/flow/template/save/action",
                            type: 'POST',
                            data: JSON.stringify(flowTemplateList),
                            dataType: "JSON",
                            contentType: 'application/json;charset=utf-8',
                            beforeSend: function () {
                                //触发ajax请求开始时执行
                                $("#doSubmit").text('提交中...');
                                $("#doSubmit").attr('disabled', 'disabled');
                            },
                            success: function (data) {
                                if (data.success) {
                                    window.location.href = "/flow/view/index";
                                } else {
                                    msgTool.error(data.msg);
                                }
                            },
                            error: function (error) {
                                msgTool.error("操作失败，请刷新当前页面后重试！");
                            },
                            complete: function () {
                                $("#doSubmit").text("保存");
                                $("#doSubmit").removeAttr('disabled');
                            }
                        });
                    }
                }
            );
        },
        view: function () {
            //协议证照
            $('#businessScopeImage').viewer({
                navbar: false,
                title: false
            });
            //身份证
            $('.IDcard').viewer({
                navbar: false,
                title: false
            });
            
        
            $("#print").on('click', function () {
            		  if (!!window.ActiveXObject || "ActiveXObject" in window) { //是否ie
            		   remove_ie_header_and_footer();
            		  }
           	$("#content").print({
            		    globalStyles: true,
            		    mediaPrint: false,
            		    stylesheet: null,
            		    noPrintSelector: ".no-print",
            		    iframe: true,
            		    append: null,
            		    prepend: null,
            		    manuallyCopyFormValues: true,
            		    deferred: $.Deferred()
            	});
            });

        },
        evaluate:function(){
            $("#saveEvaluate").on('click', function () {
            	$("#evaluateForm").submit();
            });
          
        },
        print:function () {
            /**
             * 打印
             * @param contentNode
             */
        	
            function print(contentNode) {
                if (!!window.ActiveXObject || "ActiveXObject" in window) { //是否ie
                    remove_ie_header_and_footer();
                }
             	$(contentNode).print({
              		    globalStyles: true,
              		    mediaPrint: false,
              		    stylesheet: null,
              		    noPrintSelector: ".no-print",
              		    iframe: true,
              		    append: null,
              		    prepend: null,
              		    manuallyCopyFormValues: true,
              		    deferred: $.Deferred()
              	});
            }

            $("#companyLicense").on('click', function () {
                print("#companyLicense_content");
            });

            $("#rentalContract").on('click', function () {
                print("#rentalContract_content");
            });
            
            $("#layout").on('click', function () {
                print("#layout_content");
            });
            
            $("#operatingProcedures").on('click', function () {
                print("#operatingProcedures_content");
            });
            
            $("#orientationMap").on('click', function () {
                print("#orientationMap_content");
            });
            
            
            $("#managerRlues").on('click', function () {
            	print("#managerRlues_content");
            });
            
            $("#license").on('click', function () {
                print("#license_content");
            });
            


        },
        report: function (data) {
        	var chart = Highcharts.chart('container', {
                title: {
                    text: '当月统计查询'
                },
                xAxis: {
                    categories: ['待认领', '办理中', '已拒绝','已通过']
                },
                yAxis: {
                    allowDecimals: false,
                    title: {
                        text: '数量（个）'
                    }
                },
                series: [{
                    type: 'column',
                    name: '数量',
                    colorByPoint: true,
                    data: [data.sumClaimTask,data.sumHandleTask,data.sumRefuseTask,data.sumPassTask],
                    showInLegend: false
                }]
            });

        }
    }
});






